<template>
	<div
		v-show="true"
		class="v-swiper-item"
		:class="{ 'is-active': active, 'is-animating': animating }"
		:style="itemStyle"
	>
		<slot></slot>
	</div>
</template>
<script>
export default {
	data() {
		return {
			translate: 0,
			scale: 1,
			inStage: "",
			active: false,
			ready: false,
			animating: false,
		};
	},
	name: "VSwiperItem",
	inject: ["swiper"],
	computed: {
		itemStyle() {
			const value = `translateX(${this.translate}px) scale(${this.scale})`;
			const style = {
				transform: value,
			};
			return style;
		},
	},
	created() {
		this.$parent && this.$parent.updateItems();
	},
	mounted() {},
	methods: {
		//activeIndex 0
		//3 '0'  1  2
		//activeIndex 1
		//0 '1'  2  3
		//activeIndex 2
		//1	'2' 0
		processIndex(index, activeIndex, length) {
			if (activeIndex === 0 && index === length - 1) {
				return -1;
			} else if (activeIndex === length - 1 && index === 0) {
				return length;
			} else if (index < activeIndex - 1 && activeIndex - index >= length / 2) {
				return length + 1;
			} else if (index > activeIndex + 1 && index - activeIndex >= length / 2) {
				return -2;
			}
			return index;
		},
		translateItem(index, activeIndex, oldIndex) {
			const length = this.$parent.items.length;
			if (oldIndex !== undefined) {
				this.animating = index === activeIndex || index === oldIndex;
			}

			if (index !== activeIndex && length > 2 && this.$parent.loop) {
				index = this.processIndex(index, activeIndex, length);
			}
			this.active = index === activeIndex;
			this.translate = this.calcTranslate(index, activeIndex);
			this.ready = true;
		},

		calcTranslate(index, activeIndex) {
			const distance = this.$parent.$el["offsetWidth"];
			return distance * (index - activeIndex);
		},
	},

	destroyed() {
		this.$parent && this.$parent.updateItems();
	},
};
</script>
<style lang="less" scoped>
.v-swiper-item {
	position: absolute;
	font-size: 0;
	width: 100%;
	height: 100%;
	display: inline-block;
	z-index: 0;
	&.is-active {
		z-index: 2;
	}
	&.is-animating {
		transition: transform 0.35s;
	}
}
</style>
